using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using StudentVideo.Shared.Models;

namespace StudentVideo.Filters;

public class CustomActionFilter(ILogger<HttpResultFilter> logger): IActionFilter {
   private readonly ILogger<HttpResultFilter> _logger = logger;

   public void OnActionExecuting(ActionExecutingContext context) {
      // 在 Action 执行之前调用
      // Console.Write(context);
   }

   public void OnActionExecuted(ActionExecutedContext context) {
      var result = new HttpResult<object> {
         StatusCode = 200,
         Message = "Success",
         Data = null
      };

      // 在 Action 执行之后调用
      if (context.Result is ObjectResult objectResult) {
         // 将返回结果封装到 HttpResult<T> 中
         result.Data = objectResult.Value;
         result.StatusCode = objectResult.StatusCode ?? 200;
      }

      // 替换原始的返回结果
      context.Result = new ObjectResult(result) {
         StatusCode = 200
      };
   }
}
